﻿using LDC_Shop_B.Models;
using LDC_Shop_B.Models.Database;
using System;
using System.Collections.Generic;
using System.Linq;

namespace LDC_Shop_B.Serives
{
    public class OrderService : IOrderService
    {
        private readonly LDC_ShopBContext _db;
        /// <summary>
        /// 订单服务
        /// </summary>
        /// <param name="db"></param>
        public OrderService(LDC_ShopBContext db)
        {
            _db = db;
        }

        /// <summary>
        /// 获取订单编号（年月日时分秒 + 随机数[0001-9999]） 保证订单编号唯一 
        /// </summary>
        public string GetOrderNum()
        {
            return System.DateTime.Now.ToString("yyyyMMddHHmmss") + new Random().Next(1, 10000).ToString().PadLeft(4, '0');
        }
        /// <summary>
        /// 创建订单和订单明细
        /// </summary>
        /// <param name="list"></param>
        /// <param name="userId"></param>
        public void CreateOrder(List<CarGoods> list, int userId)
        {
            //创建订单 有了
            var order = new Order
            {
                CreateTime = System.DateTime.Now,
                //订单编号 规则  时间  2023617144350+随机数
                OrderNum = GetOrderNum(),
                //订单总价
                OrderPrice = list.Sum(x => x.Price * x.Count),
                //0待付款 1待发货（已付款） 2待收货
                OrderState = (int)OrderState.待发货,
                ShipCom = string.Empty,
                ShipNum = string.Empty,
                PayTime = System.DateTime.Now,
                //数量的综合
                TotalCount = list.Sum(x => x.Count),
                UserId = userId,
            };
            //添加数据库
            _db.Orders.Add(order);
            //保存更改
            _db.SaveChanges();
            //创建订单明细 多个 循环遍历购物车去创建订单明细
            foreach (var item in list)
            {
                //通过购物车的商品 去创建明细
                var orderItem = new OrderItem
                {
                    GoodCount = item.Count,
                    GoodCover = item.Photo,
                    GoodId = item.GoodId,
                    GoodName = item.Title,
                    GoodPrice = item.Price,
                    //前提 ： 提交到数据库
                    OrderId = order.OrderId
                };
                _db.OrderItems.Add(orderItem);
            }
            //执行的时候 失败
            _db.SaveChanges();
        }
        /// <summary>
        /// 减少商品库存
        /// </summary>
        public void DiffGoodStock(List<CarGoods> list)
        {
            foreach (var item in list)
            {
                //哪个商品 item.GoodId 减少多少 item.Count
                var good = _db.Goods.FirstOrDefault(x => x.GoodId == item.GoodId);
                if (good != null)
                {
                    //减少库存-         库存  少于 买的数量
                    good.Stock = good.Stock - item.Count;
                    _db.Goods.Update(good);
                }
            }
            _db.SaveChanges();
        }
        /// <summary>
        /// 检查库存 返回库存是否足够 如果不够 提示哪个商品库存不足
        /// </summary>
        /// <param name="list">购物车</param>
        /// <param name="err">返回不足商品信息</param>
        /// <returns>是否库存不足</returns>
        public bool CheckGoodStock(List<CarGoods> list, out string err)
        {
            err = string.Empty;
            foreach (var item in list)
            {
                //哪个商品 item.GoodId 减少多少 item.Count
                var good = _db.Goods.FirstOrDefault(x => x.GoodId == item.GoodId);
                if (good != null)
                {
                    //如果库存  少于 我要买的库存
                    if (good.Stock < item.Count)
                    {
                        //不足商品的名称
                        err = good.Title;
                        //库存不足
                        return false;
                    }
                }
            }
            return true;
        }
        /// <summary>
        /// 获取用户订单列表
        /// </summary>
        public List<UserOrder> GetUserOrderList(int userId, int orderState, int pageIndex, int pageSize, out int total)
        {
            //用户下的所有订单
            var orders = _db.Orders.Where(x => x.UserId == userId);

            //判断是否查询订单状态 
            if (orderState > -1)
            {
                orders = orders.Where(x => x.OrderState == orderState);
            }
            total = orders.Count();
            var list = orders.OrderByDescending(x => x.CreateTime)
                .Skip((pageIndex - 1) * pageSize)
                .Take(pageSize)
                //输出为想要的模型
                .Select(x => new UserOrder
                {
                    OrderId = x.OrderId,
                    OrderCount = x.TotalCount,
                    OrderNum = x.OrderNum,
                    OrderPrice = x.OrderPrice,
                    OrderState = x.OrderState,
                    CreateTime = x.CreateTime,
                })
                .ToList();
            foreach (var item in list)
            {
                //每个订单的订单明细
                item.OrderItems = _db.OrderItems.Where(x => x.OrderId == item.OrderId).ToList();
            }
            return list;
        }

        /// <summary>
        /// 获取后台订单列表
        /// </summary>
        public List<AdminOrder> GetAdminOrderList(int orderState, int pageIndex, int pageSize, out int total)
        {
            //用户下的所有订单
            var orders = _db.Orders.AsQueryable();

            //判断是否查询订单状态 
            if (orderState > -1)
            {
                orders = orders.Where(x => x.OrderState == orderState);
            }
            total = orders.Count();
            var list = orders
                .Join(_db.Users,x=>x.UserId,y=>y.UserId,(x,y)=>new AdminOrder
                {
                    OrderId = x.OrderId,
                    OrderCount = x.TotalCount,
                    OrderNum = x.OrderNum,
                    OrderPrice = x.OrderPrice,
                    OrderState = x.OrderState,
                    CreateTime = x.CreateTime,
                    UserId = x.UserId,
                    Mobile=  y.Mobile,
                    NickName= y.NickName
                })
                .OrderByDescending(x => x.CreateTime)
                .Skip((pageIndex - 1) * pageSize)
                .Take(pageSize)
                .ToList();
            foreach (var item in list)
            {
                //每个订单的订单明细
                item.OrderItems = _db.OrderItems.Where(x => x.OrderId == item.OrderId).ToList();
            }
            return list;
        }

        /// <summary>
        /// 发货
        /// </summary>
        /// <param name="orderId"></param>
        /// <param name="shipCom"></param>
        /// <param name="shipNum"></param>
        /// <returns></returns>
        public bool SendOrder(int orderId,string shipCom,string shipNum)
        {
            //查询订单出来
           var order = _db.Orders.FirstOrDefault(x => x.OrderId == orderId);
            if(order!=null)
            {
                //更新订单（订单状态、快递公司、快递单号）
                order.OrderState = (int)OrderState.待收货;
                order.ShipCom = shipCom;
                order.ShipNum = shipNum;
                _db.Orders.Update(order);
                return _db.SaveChanges()>0;
            }
            return false;
        }
    }
}
